`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date: 2025/03/17 16:09:12
// Design Name: 
// Module Name: divider
// Project Name: 
// Target Devices: 
// Tool Versions: 
// Description: 
// 
// Dependencies: 
// 
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
// 
//////////////////////////////////////////////////////////////////////////////////


module divider#(
    parameter   [ 7:0]  N = 8
)(
	input					clk		,	
	input					rst_n	,	
	input					start	,	
	input		[N-1:0]		dividend,	
	input		[N-1:0]		divisor	,	
	
    output reg              finish,
	output reg  [N-1:0]		quotient,	
	output reg  [N-1:0]		remainder			
);
/****************define******************/
localparam  [2:0]   IDLE = 3'b001;
localparam  [2:0]   CALC = 3'b010;
localparam  [2:0]   DONE = 3'b100;

reg		[2*N-1:0]		dividend_temp ;
reg		[2*N-1:0]		divisor_temp;
reg     [ 2:0]          state;
reg		[$clog2(N):0]	cnt;

/**********************************/
always @(posedge clk or negedge rst_n)begin
	if(!rst_n)begin
		dividend_temp <= 'd0;
		divisor_temp <= 'd0;
		remainder <= 'd0;
		quotient <= 'd0;
		finish <= 1'b0;
		state <= IDLE;
        cnt <= 'd0;
	end
	else begin
		case(state)
			IDLE:begin
				if(start)begin
					dividend_temp <= {{N{1'b0}},dividend};
					divisor_temp <= {divisor,{N{1'b0}}};
					state <= CALC;
				end
			end
			CALC:begin
				if(cnt == N) begin    
                    remainder <= dividend_temp[2*N-1:N];
                    quotient <= dividend_temp[N-1:0];
                    finish <= 1'b1;
					state <= DONE;
				end
				else begin
				    cnt <= cnt + 1'b1;
					if(dividend_temp[2*N-2:N-1] >= divisor_temp[2*N-1:N])
						dividend_temp <= {dividend_temp[2*N-2:0],1'b0} - divisor_temp + 1'b1;
					else 
						dividend_temp <= {dividend_temp[2*N-2:0],1'b0};
				end
			end
            DONE:begin
                finish <= 1'b0;	
                state <= IDLE;	
                cnt <= 'd0;	 
			end
		endcase
	end	
end


endmodule

